package com.ptit.piclient.tools;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;

import com.ptit.piclient.model.*;

public class PiConnector {

	/**
	 * @param args
	 */
	private URL url;
	private HttpURLConnection urlConnection;
	private static PiConnector instance = null;
	private PiConnector(){
			try{
				url = new URL("http://192.168.1.2/jsonrpc");
				urlConnection = (HttpURLConnection) url
						.openConnection();
				urlConnection.setRequestMethod("POST");
				urlConnection.setRequestProperty("Content-Type",
						"application/json; charset=utf-8");
				urlConnection.setRequestProperty("Content-Language", "vi-VN");
				urlConnection.setUseCaches(false);
				urlConnection.setDoInput(true);
				urlConnection.setDoOutput(true);
			}catch(Exception e){}
	}
	public static PiConnector getInstance(){
		if(instance == null) instance = new PiConnector();
		return instance;		
	}
    public ArrayList<Song> getAllSongs(){
		ArrayList<Song> songlist = new ArrayList<Song>();
		StringBuffer response = new StringBuffer();
		try{
		DataOutputStream das = new DataOutputStream(
				urlConnection.getOutputStream());
		das.writeBytes("{\"jsonrpc\": \"2.0\", \"method\": \"AudioLibrary.GetSongs\"," +
				" \"params\": { \"limits\": { \"start\" : 0 }, \"properties\": [ \"artist\", \"duration\", \"album\", \"track\" ], \"sort\": { \"order\": \"ascending\", \"method\": \"track\", \"ignorearticle\": true } }, \"id\": \"getsongs\"}");

		das.flush();
		das.close();

		InputStream is = urlConnection.getInputStream();
		BufferedReader rd = new BufferedReader(new InputStreamReader(is));
		String line;

		while ((line = rd.readLine()) != null) {
			response.append(line);
			response.append('\r');
		}
		rd.close();

		JSONObject jO = new JSONObject(response.toString());
		// .out.println(response.toString());
		JSONObject result = jO.optJSONObject("result");
		JSONArray array = result.optJSONArray("songs");
		JSONObject t;
		
		
		for (int i = 0; i < array.length(); i++) {
			t = array.getJSONObject(i);				
			Song s = new Song();
			s.setAlbum(t.optString("album"));
			s.setDuration(t.optInt("duration"));
			s.setName(t.optString("label"));

			songlist.add(s);
		}
		}catch(Exception e){}
		return songlist;		
	}
	
	public void playsong(int i){
		try{
			DataOutputStream das = new DataOutputStream(
					urlConnection.getOutputStream());
			das.writeBytes("{\"jsonrpc\": \"2.0\", \"method\": \"Player.GetActivePlayers\", \"id\": 1}");
			
			StringBuffer response = new  StringBuffer();
			InputStream is = urlConnection.getInputStream();
			BufferedReader rd = new BufferedReader(new InputStreamReader(is));
			String line;
	
			while ((line = rd.readLine()) != null) {
				response.append(line);
				response.append('\r');
			}
			rd.close();
			
			if(!response.toString().contains("audio")){
				das.writeBytes("{\"jsonrpc\": \"2.0\", \"method\": \"Player.Open\"," +
						" \"id\": 1, \"params\":\"{\"item\":{\"playlistid\": "+0 + "} }\"}");
			}
			
			das.flush();
			das.close();
		}catch(Exception e){}		
	}
	
	/**
	 * Add song to library
	 */
	
}
